/*
 * @Description: 
 * @Author: fhw
 * @Date: 2022-11-18 16:39:53
 */
import { ConnectedSocket, MessageBody, SubscribeMessage, WebSocketGateway, WebSocketServer } from '@nestjs/websockets';
import { GroupChatRecord } from 'src/chat-record/entities/group-chat-record.entity';
import { GroupChatService } from 'src/group-chat/group-chat.service';
import { HistorySessionService } from 'src/history-session/history-session.service';
import { SocketType } from 'src/utlis';
import { ConfigService } from '../config/config.service';
import { SocketFriendChatGateway } from '../socket-friend-chat/socket-friend-chat.gateway';
import { GroupChatMessageDto } from './dto/socket-room.dto';
import { SocketRoomService } from './socket-room.service';

@WebSocketGateway({
  allowEIO3: true,
  cors: {
    origin: /.*/,
    credentials: true,
  },
})
export class SocketRoomGateway {
  constructor(
    private readonly socketRoomService: SocketRoomService,
    public readonly configService: ConfigService,
    public readonly groupChatService: GroupChatService,
    private readonly socketFriendChatGateway: SocketFriendChatGateway,
  ) { }
  /** 用户获取到群聊信息则直接加入群聊房间 */
  @WebSocketServer() server: any
  @SubscribeMessage('groupChatLogin')
  async groupChatLogin(@MessageBody() { userId, group_id }, @ConnectedSocket() clinet) {
    this.configService.setRoom(group_id, userId)
    clinet.join(group_id)
    this.server.emit('groupChatLogin', { connectCounts: this.configService.getRoom(group_id).length })
  }
  /** 有bug，待处理：.emit undefined*/
  // async handleDisconnect(@MessageBody() { userId, group_id }, @ConnectedSocket() clinet) {
  //   this.configService.delRoomUserId(group_id, userId)
  //   clinet.emit('groupChatLeave')
  // }
  /** 发送群聊消息 */
  @SubscribeMessage('groupChatMessage')
  async groupChatMessage(@MessageBody() params: GroupChatMessageDto, @ConnectedSocket() clinet) {
    /**
     * 思路
     * 1.接受消息写入数据库
     * 2.更新群聊最新消息
     * 3.群聊成员未读记录 +1，发送者无需增加
     * 4.通知成员有未读消息
     * 5.广播所有群成员
     */
    const { group_id, userId } = params
    // 接受消息写入数据库
    const data = await this.socketRoomService.groupChatMessage(params) as GroupChatRecord | SocketType;
    // 写入聊天记录报错返回报错信息
    if ((data as SocketType).success === false) {
      clinet.emit('socketError', data);
      return
    }
    // 更新群聊最新消息
    await this.groupChatService.updateGroupChatRecordLatestNews({ group_id }, data as GroupChatRecord)
    // 群聊成员未读记录 +1，发送者无需增加
    await this.socketRoomService.updateChatUserGroup(group_id, userId)
    const chatUserGrouplist = await this.socketRoomService.getChatUserGroup(group_id)
    chatUserGrouplist.forEach(item => {
      this.socketFriendChatGateway.getChatUnreadRecord(item.userId)
    })
    this.server.of('/').to(group_id).emit('acceptGroupChatMessage', data);
  }
}
